import axios from 'axios';
import store from '@/store'
import { Toast } from 'vant';
import router from '@/router';

let baseUrl
if (process.env.NODE_ENV === 'development') {
  baseUrl = 'http://toutiao-app.itheima.net/'
}

const request = axios.create({
  baseURL: baseUrl,
  timeout: 5000,
})
//axios设置请求拦截器
axios.interceptors.request.use(config => {
  config.headers['Authorization'] = "Bearer " + store.getters.token
  return config
}, err => {
  console.log(err)
})
//axios设置响应拦截器
request.interceptors.response.use(response => {
  return response.data //拦截处理响应结果，直接返回需要的数据
}, err => {
  if (err && err.response && err.response.status === 429) {
    Toast({
      message: '请求过于频繁, 请稍后',
      position: 'top'
    })
    return Promise.reject(new Error('请求过于频繁, 请稍后'))
  }
  if (err && err.response && err.response.status === 401) {
    Toast({
      message: '登录过期, 请重新登录',
      position: 'top'
    })
    router.push('/login')
  }
})
export default request